package com.ltxtiyu.video.tool;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class ParamTool {
    private static final Logger LOGGER = LoggerFactory.getLogger(ParamTool.class);
    /**
     * request参数封装到map
     * @param request
     * @return
     */
    public static Map<String, String> requestToParamMap(HttpServletRequest request) {
        Map<String, String> paramMap = new HashMap<String, String>();
        Enumeration enu = request.getParameterNames();
        while(enu.hasMoreElements()){
            String paramName = (String)enu.nextElement();
            if(StringUtils.isNotBlank(request.getParameter(paramName)) ){
                paramMap.put(paramName,request.getParameter(paramName));
            }
        }
        return paramMap;
    }

    /**
     * bean转换成map
     * @param bean
     * @return
     */
    public static Map beanToMap(Object bean){
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Class<?> clazz = bean.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(bean);
                map.put(fieldName, value);
            }
            // 获取父属性
            Class<?> superclass = clazz.getSuperclass();
            for (Field field : superclass.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(bean);
                map.put(fieldName, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
